﻿<!DOCTYPE html>
<head>
    <meta charset="UTF-8">

    <script src="https://code.jquery.com/jquery-3.5.1.min.js"
            integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

    <script type="text/javascript">

        "use strict";

        const STUN_URL = "stun:stun.sipsorcery.com";
        const NODE_DSS_URL = "http://127.0.0.1:3000";
        const NODE_DSS_OUR_ID = "console";
        const NODE_DSS_THEIR_ID = "unity";
        const NODE_DSS_POLL_PERIOD = 5000;

        var pc;
        var nodeDssUrl = NODE_DSS_URL;
        var nodeDssOurID = NODE_DSS_OUR_ID;
        var nodeDssTheirID = NODE_DSS_THEIR_ID;
        var isClosed = false;

        $(document).ready(function () {
            $('#nodedssurl').val(NODE_DSS_URL);
            $('#ourID').val(NODE_DSS_OUR_ID);
            $('#theirID').val(NODE_DSS_THEIR_ID);
        });

        async function start() {
            isClosed = false;
            pc = new RTCPeerConnection({ iceServers: [{ urls: STUN_URL }] });

            pc.ontrack = evt => document.querySelector('#videoCtl').srcObject = evt.streams[0];
            pc.onicecandidate = evt => evt.candidate && sendSignal(JSON.stringify(evt.candidate));

            // Diagnostics.
            pc.onicegatheringstatechange = () => console.log("onicegatheringstatechange: " + pc.iceGatheringState);
            pc.oniceconnectionstatechange = () => console.log("oniceconnectionstatechange: " + pc.iceConnectionState);
            pc.onsignalingstatechange = () => console.log("onsignalingstatechange: " + pc.signalingState);
            pc.onconnectionstatechange = () => console.log("onconnectionstatechange: " + pc.connectionState);

            nodeDssUrl = $('#nodedssurl').val();
            nodeDssOurID = $('#ourID').val();
            nodeDssTheirID = $('#theirID').val();

            pollNodeDss();
        };

        function sendSignal(msg) {
            //console.log(`sendSignal ${msg}`);

            $.ajax({
                url: `${nodeDssUrl}/data/${nodeDssTheirID}`,
                type: 'POST',
                contentType: 'application/json',
                data: msg,
                success: onSuccess,
                error: onError
            });
        }

        async function pollNodeDss(delayms) {
            if (delayms > 0) {
                await new Promise(r => setTimeout(r, delayms));
            }

            if (!isClosed) {
                $.ajax({
                    url: `${nodeDssUrl}/data/${nodeDssOurID}`,
                    type: 'GET',
                    success: onSuccess,
                    error: onError
                });
            }
        }

        async function onSuccess(data, status) {
            //console.log(`${status}: ${data}`);
            if (/^[\{"'\s]*candidate/.test(data)) {
                pc.addIceCandidate(JSON.parse(data));
            }
            else if (/^[\{"'\s]*type/.test(data)) {
                let sdpInit = JSON.parse(data);
                console.log(`Received remote SDP offer.`)
                await pc.setRemoteDescription(new RTCSessionDescription(sdpInit));
                if (pc.localDescription == null) {
                    await pc.createAnswer()
                        .then((answer) => pc.setLocalDescription(answer))
                        .then(() => { sendSignal(JSON.stringify(pc.localDescription)) });
                }
            }
             pollNodeDss(NODE_DSS_POLL_PERIOD);
        }

       async function onError(xhr, status, error) {
            if (!isClosed && error == "Not Found" && pc.localDescription == null) {
                pollNodeDss(NODE_DSS_POLL_PERIOD);
            }
            else {
                console.log(`${status}: ${error}`);
            }
        }

        async function closePeer() {
            isClosed = true;
            await pc.close();
        };

    </script>
</head>
<body>

    <video controls autoplay="autoplay" id="videoCtl" width="640" height="480"></video>

    <div>
        <label>Node DSS URL:</label> <input type="text" id="nodedssurl" size="40" /><br />
        <label>Our ID:</label> <input type="text" id="ourID" size="10" /><br />
        <label>Their ID:</label> <input type="text" id="theirID" size="10" /><br />
        <button type="button" class="btn btn-success" onclick="start();">Start</button>
        <button type="button" class="btn btn-success" onclick="closePeer();">Close</button>
    </div>

</body>
